package com.payment_server.controller;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.payment_server.entity.PaymentOrderEntity;
import com.payment_server.util.QRCodeGenerator;
import com.payment_server.util.RedisUtil;
import com.payment_server.util.responseUtil.ResponseUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;
import java.util.Map;

@RestController
public class PaymentCreate {
    private Log log = LogFactory.getLog("三岁小仙仙");

    @RequestMapping("/")
    public Object requestPayment(@RequestBody Map<String, Object> body, HttpServletRequest request) throws Exception {
        //验证前端请求订单数据完整性，但不能验证订单数据的有效性，需要用户根据业务自行判断
        if (!DigestUtil.md5Hex(body.get("order").toString()).equals(body.get("hashCode").toString()))
            return new ResponseUtil<>().MD5_VERIFY_FAIL(null, null);

        //----用户自定义判断逻辑

        //----用户自定义判断逻辑

        //序列化订单信息
        JSONObject jsonObject = JSON.parseObject(body.get("order").toString(), Feature.OrderedField);
        PaymentOrderEntity paymentOrderEntity = JSON.toJavaObject(jsonObject, PaymentOrderEntity.class);

        //随机生成用户订单ID--服务端保存
        String UUID = RandomUtil.randomString(16);
        //加密UUID--返回前端使用
        //String MD5_UUID = DigestUtil.md5Hex(UUID);
        //计算访笔订单总价
        String payPrice = calcPrice(paymentOrderEntity);

        //前端支付码内容信息
        JSONObject info = new JSONObject(true);
        info.put("UUID", UUID);
        info.put("payPrice", payPrice);
        info.put("createDate", paymentOrderEntity.getCreateDate());
        info.put("expireMinutes", paymentOrderEntity.getExpireMinutes());
        String md5Data = UUID + payPrice + paymentOrderEntity.getCreateDate() + paymentOrderEntity.getExpireMinutes();
        info.put("hashCode", DigestUtil.md5Hex(md5Data));

        //前端支付码图片生成
        byte[] paymentCode = QRCodeGenerator.getQRCodeImage(info.toJSONString(), 300, 300);
        BASE64Encoder encoder = new BASE64Encoder();
        String img = "data:image/jpg;base64," + encoder.encode(paymentCode);

        //服务端保存真正UUID
        RedisUtil.getRedisDS().setex(UUID, 60 * paymentOrderEntity.getExpireMinutes(), DigestUtil.md5Hex(md5Data));

        //返回前端信息显示
        JSONObject response = new JSONObject(true);
        response.put("img", img);
        response.put("UUID", UUID);
        response.put("payPrice", payPrice);
        return new ResponseUtil<>().OK(null, response);
    }

    private String calcPrice(PaymentOrderEntity paymentOrderEntity) {
        Iterator<Map> iterator = paymentOrderEntity.getData().iterator();
        float price = 0;
        while (iterator.hasNext()) {
            Map next = iterator.next();
            price += NumberUtil.parseFloat(next.get("number").toString()) *
                    NumberUtil.parseFloat(next.get("price").toString());
        }
        return String.valueOf(price);
    }

}
